//
//  UIViewController+Extension.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import UIKit
import Then

fileprivate enum NavigationBarButtonType {
    case left
    case right
}

public extension UIViewController {
    
    var width: CGFloat {
        return view.bounds.width
    }
    
    var height: CGFloat {
        return view.bounds.height
    }
    
    var aspectRatio: CGFloat {
        return view.bounds.width / view.bounds.height
    }
}

public extension UIViewController {
    
    /// 为控制器添加导航按钮
    ///
    /// - Parameters:
    ///   - barButtonType: 按钮位置
    ///   - image: 图片
    ///   - action: 方法
    ///   - size: 图片大小
    fileprivate func addBarButton(_ barButtonType: NavigationBarButtonType,
                                  image: UIImage?,
                                  action: Selector,
                                  size: CGSize) {
        let button = UIButton(type: .custom)
        // 去除button点击下去的 灰色阴影效果
        button.adjustsImageWhenHighlighted = false
        button.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        button.setImage(image, for: .normal)
        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: barButtonType == .left ? -25 : 0, bottom: 0, right: 0)
        button.addTarget(self, action: action, for: .touchUpInside)
        let barButton = UIBarButtonItem(customView: button)
        switch barButtonType {
        case .left:
            navigationItem.leftBarButtonItem = barButton
            break
        case .right:
            navigationItem.rightBarButtonItem = barButton
            break
        }
    }
    /// 为控制器添加导航按钮
    ///
    /// - Parameters:
    ///   - barButtonType: 按钮位置
    ///   - text: 文字
    ///   - action: 方法
    ///   - textColor: 文字颜色
    ///   - font: 字体
    fileprivate func addBarButton(_ barButtonType: NavigationBarButtonType,
                                  text: String,
                                  action: Selector,
                                  textColor: UIColor,
                                  font: UIFont) {
        let button = UIButton(type: .custom)
        button.setTitle(text, for: .normal)
        button.setTitleColor(textColor, for: .normal)
        button.addTarget(self, action: action, for: .touchUpInside)
        button.titleLabel?.font = font
        button.sizeToFit()
        let barButton = UIBarButtonItem(customView: button)
        switch barButtonType {
        case .left:
            navigationItem.leftBarButtonItem = barButton
        case .right:
            navigationItem.rightBarButtonItem = barButton
        }
    }
    
    /// 为控制器添加左边导航按钮
    func addLeftBarButton(_ image : UIImage?,
                                 action : Selector,
                                 size : CGSize = CGSize(width: 44, height: 44)) {
        addBarButton(.left, image: image, action: action, size: size)
    }
    
    /// 为控制器添加左边导航按钮
    func addLeftBarButton(_ text:String,
                                 action : Selector,
                                 textColor : UIColor = UIColor.white,
                                 font : UIFont = Font.dp(15)) {
        addBarButton(.left, text: text, action: action, textColor: textColor, font: font)
    }
    
    /// 为控制器添加右边导航按钮
    func addRightBarButton(_ image : UIImage?,
                                  action : Selector,
                                  size : CGSize = CGSize(width: 44, height: 44)) {
        addBarButton(.right, image: image, action: action, size: size)
    }
    
    /// 为控制器添加右边导航按钮
    func addRightBarButton(_ text:String,
                                  action : Selector,
                                  textColor : UIColor = UIColor.white,
                                  font : UIFont = Font.dp(15)) {
        addBarButton(.right, text: text, action: action, textColor: textColor, font: font)
    }
    
    /// 为控制器添加标题
    ///
    /// - Parameters:
    ///   - text: 文字
    ///   - textColor: 颜色
    ///   - font: 字体
    func setNavigationTitle(_ text:String?, _ textColor:UIColor = .white, _ font:UIFont = Font.dp(15)) {
        let label = UILabel(frame: CGRect.zero)
        label.text = text
        label.font = font
        label.textColor = textColor
        label.sizeToFit()
        navigationItem.titleView = label
    }
    
    /// 为控制器添加富文本标题
    ///
    /// - Parameters:
    ///   - title: 富文本
    ///   - clickAction: 点击事件
    func setNavigationAttributedTitle(with title: NSAttributedString, clickAction: Selector?) {
        let titleLabel : UILabel! = UILabel().then {
            $0.frame = CGRect(x: 0, y: 0, width: 160, height: 44)
            $0.numberOfLines = 0
            $0.textAlignment = .center
            $0.backgroundColor = UIColor.clear
            $0.isUserInteractionEnabled = true
            $0.attributedText = title
        }
        if let action = clickAction {
            let titleGesture = UITapGestureRecognizer(target: self, action:action)
            titleLabel.addGestureRecognizer(titleGesture)
            
        }
        navigationItem.titleView = titleLabel
        navigationItem.titleView?.sizeToFit()
    }
    
    /// 为控制器添加TitleView以及点击事件
    ///
    /// - Parameters:
    ///   - titleView: 视图
    ///   - clickAction: 点击事件
    func setTitleView(with titleView: UIView?, clickAction: Selector?) {
        
        if let view = titleView, let action = clickAction {
            let titleGesture = UITapGestureRecognizer(target: self, action:action)
            view.addGestureRecognizer(titleGesture)
            navigationItem.titleView = titleView
            navigationItem.titleView?.sizeToFit()
        }
    }
    
    /// 避免自动下移64
    func avoidAutomaticDown64() {
        extendedLayoutIncludesOpaqueBars = true
        edgesForExtendedLayout = .all
        automaticallyAdjustsScrollViewInsets = false
    }
    
    /// 隐藏返回按钮
    func hiddenBackBtn() {
        navigationItem.leftBarButtonItem = nil
        navigationItem.hidesBackButton = true
    }
}

public extension NSObject {
    
    /// stotyboard中获取到该控制器
    func storyboardVC<T: UIViewController>(sbName: String, vcID: T.Type ) -> T? {
        let vc = UIStoryboard(name: sbName, bundle: nil).instantiateViewController(withIdentifier: "\(vcID.self)")
        guard let targetVc = vc as? T else { return nil }
        return targetVc
    }
}

public extension UIViewController {

    /// 获取根控制器
    var rootViewController: UIViewController? {
        if let tabbarVc = self as? UITabBarController,
            let vc = tabbarVc.selectedViewController {
            return vc
        } else if let navigationVc = navigationController,
            let vc = navigationVc.topViewController {
            return vc
        } else if let vc = presentedViewController {
            return vc
        }
        return self
    }
    
    // 存在与控制器栈里
    func existStack(_ vcType: UIViewController.Type) -> Bool {
        var exist: Bool = false
        navigationController?.viewControllers.forEach {
            if $0.isKind(of: vcType) { exist = true }
        }
        return exist
    }
    
    /// 从导航栈中销毁指定控制器
    /// - Parameter type: 控制器
    func dealloc(_ type: UIViewController.Type) {
        // 销毁蓝牙连接页
        guard let marr = navigationController?.viewControllers else { return }
        var newArr: [UIViewController] = []
        for i in 0..<marr.count {
            if !marr[i].isKind(of: type.self) {
                newArr.append(marr[i])
            }
        }
        navigationController?.viewControllers = newArr
    }
    
    // push
    func push_yb(_ vc: UIViewController) {
        DispatchQueue.main.async { [weak self] in
            // 主线程 TODO:
            self?.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    // pop方法
    func pop_yb() {
        DispatchQueue.main.async { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
    }
    
    // present方法
    func present_yb(_ vc: UIViewController) {
        DispatchQueue.main.async { [weak self] in
            // 主线程 TODO:
            self?.present(vc, animated: true, completion: nil)
        }
    }
    
    // dismiss方法
    func dismiss_yb() {
        dismiss(animated: true, completion: nil)
    }
    
    /// pop回制定控制器
    func popToControl<C: UIViewController>(vc: C.Type, result: BlockSingleBool? = nil) {
        guard let controls = navigationController?.viewControllers else {
            result?(false)
            return
        }
        for controller in controls where controller.isKind(of: C.self) {
            result?(true)
            _ = navigationController?.popToViewController(controller, animated: true)
            return
        }
        result?(false)
    }
    
    // 禁用右滑返回手势
    func popGestureClose() {
        //禁止当前画面 右划返回
        let traget = self.navigationController?.interactivePopGestureRecognizer!.delegate;
        let pan  = UIPanGestureRecognizer.init(target: traget, action: nil);
        self.view.addGestureRecognizer(pan)
    }
}
